package com.yb.login.center.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yb.auth.core.bean.SysPermission;
import com.yb.auth.core.bean.SysUser;
import com.yb.core.constant.HttpConstant;
import com.yb.login.center.mapper.SysUserMapper;
import com.yb.login.center.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * Copyright (C), 2022-2022, 姚兵
 * Author: 32210
 * Date: 2022/11/13 17:03
 * FileName: SysUserServiceImpl
 * Description:
 */
@Service
@Slf4j
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        log.info("username:{}",username);
        if(!StringUtils.hasText(username)){
            throw new UsernameNotFoundException(HttpConstant.Response.USER_EMPTY.getMsg());
        }
        SysUser sysUser = this.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, username));
        if(Objects.isNull(sysUser)){
            throw new UsernameNotFoundException(HttpConstant.Response.USER_NOT_EXISTS.getMsg());
        }
        log.info("sysUser:{}", JSONObject.toJSONString(sysUser));
        //查询权限集合
        List<SysPermission> permissions = this.baseMapper.selectUserPerms(sysUser.getId());

        log.info("permissions:{}",JSONObject.toJSONString(permissions));
        return new SysUser(sysUser,permissions.stream().map(item->item.getName()).collect(Collectors.toList()));
    }


    @Override
    public UserDetails loadUserByMobile(String mobile) {
        log.info("mobile:{}",mobile);
        if(!StringUtils.hasText(mobile)){
            throw new UsernameNotFoundException(HttpConstant.Response.MOBILE_ERROR.getMsg());
        }
        SysUser sysUser = this.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getMobile, mobile));
        if(Objects.isNull(sysUser)){
            throw new UsernameNotFoundException(HttpConstant.Response.USER_NOT_EXISTS.getMsg());
        }
        log.info("sysUser:{}", JSONObject.toJSONString(sysUser));
        //查询权限集合
        List<SysPermission> permissions = this.baseMapper.selectUserPerms(sysUser.getId());

        log.info("permissions:{}",JSONObject.toJSONString(permissions));
        return new SysUser(sysUser,permissions.stream().map(item->item.getName()).collect(Collectors.toList()));
    }
}
